package io.renren.modules.basedata.service.impl;

import cn.com.taiji.common.manager.net.http.binclient.ApiRequestException;
import cn.com.taiji.sdk.comm.ETCCommHelper;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.server.TollLaneUploadRequest;
import cn.com.taiji.sdk.model.comm.protocol.sdts.basics.server.TollLaneUploadResponse;
import io.renren.common.utils.CompletionStr;
import io.renren.common.utils.DateUtil;
import io.renren.common.utils.GUID;
import io.renren.modules.basedata.dao.OperlogDao;
import io.renren.modules.basedata.dao.TollLaneUploadDao;
import io.renren.modules.basedata.entity.tbl_Operlog;
import io.renren.modules.basedata.entity.tbl_tollLane;
import io.renren.modules.basedata.service.TollLaneUploadService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author djz
 * @version 上传收费车道信息
 */
@Service
public class TollLaneUploadServiceImpl implements TollLaneUploadService {

	private static final Logger log = Logger.getLogger(TollLaneUploadServiceImpl.class);

	@Autowired
	TollLaneUploadDao tollLaneUploadDao;
	@Autowired
	OperlogDao operlogDao;

	@Override
	public String tollLaneUpload() throws Exception {
		log.info("开始获取收费车道信息！");
		int operResult = 0;
		List<tbl_tollLane> list = null;
		tbl_tollLane tollLane = null;
		tbl_Operlog operlog = new tbl_Operlog();
		list = getTollLaneList();//获取收费车道信息
		if(list!=null&&list.size()>0){
			for(int i=0;i<list.size();i++){
				tollLane = list.get(i);
				//收费车道信息上传及变更接口
				TollLaneUploadRequest request = new TollLaneUploadRequest();
				request.setId(tollLane.getId());
				request.setType(tollLane.getType());
				request.setGreenTraffic(tollLane.getGreenTraffic());
				request.setTidalTime(tollLane.getTidalTIme());
				request.setStartTime(DateUtil.formatDate(tollLane.getStartTime()));
				request.setEndTime(DateUtil.formatDate(tollLane.getEndTime()));
				request.setStatus(tollLane.getStatus());
				request.setOperation(tollLane.getFlag());
				//新增  --先注释掉(等新接口)
				String laneHex = getLaneHex(tollLane);
				tollLane.setLaneHex(laneHex);
				request.setLaneHex(laneHex);
				request.setRSUManUID(tollLane.getRSUManUID());
				request.setRSUModel(tollLane.getRSUModel());
				request.setRSUID(tollLane.getRSUId());
				request.setRSUVerID(tollLane.getRSUVerId());
				
				//获取发送文件名
				String fileName = ETCCommHelper.getFileName(request,"65");

				try{
					//指定响应的协议模型,调用upload发送数据
					TollLaneUploadResponse response = ETCCommHelper.sdtsUpload(fileName, request,TollLaneUploadResponse.class );
					log.info("上传收费车道信息成功,服务器返回:"+response.toJson());
					if(response!=null&&response.getInfo().equals("成功！")){
						//更新上传标志

						if(tollLaneUploadDao.updateTollLane(tollLane)==1){
							log.info("更新收费车道信息表上传标志成功!");
							operResult = 1;
							operlog = getOperlog(28,1,tollLane.getId(),fileName ,operResult, response.getInfo(),"上传成功,更新成功");
						}else{
							log.info("更新收费车道信息表上传标志失败!");
							operlog = getOperlog(28,1,tollLane.getId(),fileName ,operResult,response.getInfo(),"上传成功,更新失败");
							operlogDao.insertlog(operlog);
							//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
						}
//						sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					}else{
						log.info("上传收费车道信息失败!失败原因:"+response.getInfo());
						tollLaneUploadDao.updateTollLaneError(tollLane.getId());
						//sqlMapClient.update("tollBaseInfo_ORACLE.updateTollLaneError",tollLane.getId());
						
						//getOperlog（操作类型,传输类型,发送文件名,接收文件名,操作结果,部中心返回结果,说明）
						operlog = getOperlog(28,1 ,tollLane.getId(),fileName ,0,response.getInfo(), response.toJson());
						operlogDao.insertlog(operlog);
						//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					}
				}catch(IOException e){
					log.error("上传收费车道信息失败！错误信息:"+e.getMessage());
					
//					sqlMapClient.update("tollBaseInfo_ORACLE.updateTollLaneError",tollLane.getId());
					
					operlog = getOperlog(28, 1, tollLane.getId(), fileName, 0,"IO异常", "出现IO异常,数据上传失败:"+e.getMessage());
					operlogDao.insertlog(operlog);
					//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					e.printStackTrace();
					continue;
				}catch (ApiRequestException apie) {
					log.error("上传收费车道信息失败！错误信息:"+apie.getMessage());
					
					if(apie.getErrCode()>=700&&apie.getErrCode()<=800){
						tollLaneUploadDao.updateTollLaneError(tollLane.getId());
						//sqlMapClient.update("tollBaseInfo_ORACLE.updateTollLaneError",tollLane.getId());
					}
					
					operlog = getOperlog(28, 1, tollLane.getId(), fileName, 0,String.valueOf(apie.getErrCode()), "出现Apie异常,数据上传失败:"+apie.getMessage());
					operlogDao.insertlog(operlog);
					//sqlMapClient.insert("operlog_ORACLE.insertlog",operlog);
					apie.printStackTrace();
					continue;
				}
			}
				return "上传收费车道信息结束！";
		}else{
			return "无收费车道信息,上传结束...";
		}
	}
	
	//获取收费车道信息
	@SuppressWarnings("unchecked")
	public List<tbl_tollLane> getTollLaneList() throws IOException{
		List<tbl_tollLane> list;
		try{
			list  = tollLaneUploadDao.getTollLaneList();
			//list = sqlMapClient.queryForList("tollBaseInfo_ORACLE.getTollLaneList");
		}catch(Exception e){
			e.printStackTrace();
			log.error("获取收费车道信息失败！错误信息:",e);
			throw new IOException("获取收费车道信息失败:"+e.getMessage());
		}
		return list;
	}
	
	//获取operlog信息
	public tbl_Operlog getOperlog(int operType,int softType,String sendFileName,String reFileName,int operResult,String reResult, String content){
		tbl_Operlog operlog = new tbl_Operlog();
		operlog.setWastesn(new GUID().toString());
		operlog.setOperTime(new Date());
		operlog.setOpertype(operType);
		operlog.setSoftType(softType);
		operlog.setSendFileName(sendFileName);
		operlog.setReFileName(reFileName);
		operlog.setOperResult(operResult);
		operlog.setReResult(reResult);
		operlog.setContent(content);
		return operlog;
	}
	
	/**
	 *获取收费车道HEX码   6501010  103
	 * STATIONHEX = 6501(10转16)+01010(10转16) +103(10转16)
	 */
	public String getLaneHex(tbl_tollLane tollLane){
		 String provinceId = Integer.toHexString(6501);
		 String stationId = CompletionStr.compStr0(Integer.toHexString(Integer.valueOf(tollLane.getOldstationid().substring(2))),4) ;
		 String laneId = CompletionStr.compStr0(Integer.toHexString(Integer.valueOf(tollLane.getOldlaneid())),2) ;
	     return (provinceId+stationId+laneId);
	}
}
